package com.nsgf.library.ui.product;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.viewpager2.widget.ViewPager2;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.binding_state.BR;
import com.netease.yunxin.app.im.message.ProductMessageUtils;
import com.netease.yunxin.kit.alog.ALog;
import com.nsgf.library.data.bean.Shop;
import com.zhht.htzx.R;
import com.nsgf.library.data.bean.ProductDetailBean;
import com.nsgf.library.data.bean.XBannerBeanInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.zhht.htzx.databinding.ActivityProductDetailBinding;
import com.nsgf.library.dialog.ProductSpecDialog;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.glide.GlideImgManager;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;


public class ProductDetailActivity extends BaseActivity {

    private StateHolder mStates;

    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = new StateHolder();
        mAccountRequester = new AccountRequester();
    }

    private ActivityProductDetailBinding mBinding;

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_product_detail, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy());
    }


    private List<XBannerBeanInfo> banners = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getLifecycle().addObserver(mAccountRequester);

        mBinding = (ActivityProductDetailBinding) getBinding();

        mStates.titleBar.set("商品详情");

        mAccountRequester.productDetails(getIntent().getStringExtra("id"));

        mAccountRequester.getProductDetailResult().observe(this, new Observer<ResponseStatus<ProductDetailBean>>() {
            @Override
            public void onChanged(ResponseStatus<ProductDetailBean> productDetail) {

                if (productDetail.getResponseCode() == 0) {

                    mBinding.setVmInfo(productDetail.getData());

                    for (int i = 0; i < productDetail.getData().getSliderPicUrls().size(); i++) {
                        XBannerBeanInfo info = new XBannerBeanInfo(productDetail.getData().getSliderPicUrls().get(i));
                        banners.add(info);
                    }
                    mBinding.xbanner.setBannerData(banners);
                    mBinding.xbanner.loadImage((banner, model, view, position) -> {
                        String url = (String) ((XBannerBeanInfo) model).getXBannerUrl();
                        GlideImgManager.getInstance().glideLoaderBannerCenterCrop(ProductDetailActivity.this,
                                url.replace("\\", "/"), (ImageView) view, 10);

                    });
                    try {
                        setUpWebView(mBinding.webView.getWebView(), productDetail.getData().getDescription());
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }

                    setupListeners(productDetail.getData());
                } else {

                }

            }
        });


    }

    public static void setUpWebView(WebView wv_detail, String content) throws UnsupportedEncodingException {
        String text = URLDecoder.decode(content, "UTF-8");
        //**************处理web页面**********************
        String str1 = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "\t<head>\n" +
                "\t\t<meta charset=\"utf-8\">\n" + "<style>img{max-width:100% !important;}</style>" +
                "\t\t<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1, user-scalable=no\"></head><body>\n";
        String str2 = "</body><html>";
        wv_detail.getSettings().setDefaultTextEncodingName("UTF-8");
        WebSettings settings = wv_detail.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        //控制webView不要出现横向滚动条
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        wv_detail.setVerticalScrollBarEnabled(false);
        wv_detail.setVerticalScrollbarOverlay(false);
        wv_detail.setHorizontalScrollBarEnabled(false);
        wv_detail.setHorizontalScrollbarOverlay(false);
        if (!TextUtils.isEmpty(text)) {
            wv_detail.loadDataWithBaseURL("A", str1 + text + str2, "text/html",
                    "UTF-8", null);
            wv_detail.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return super.shouldOverrideUrlLoading(view, url);
                }
            });
        }
        wv_detail.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return true;
            }
        });
    }

    private void setupListeners(ProductDetailBean productDetail) {
        // 规格选择点击事件
        findViewById(R.id.layoutSpec).setOnClickListener(v -> showSpecDialog(productDetail, null));

        // 加入购物车按钮点击事件
        mBinding.btnAddToCart.setOnClickListener(v -> showSpecDialog(productDetail, true));

        // 立即购买按钮点击事件
        mBinding.btnBuyNow.setOnClickListener(v -> showSpecDialog(productDetail, false));
    }

    private ArrayList<Shop.ValidListBean> shops = new ArrayList<>();

    private void showSpecDialog(ProductDetailBean productDetail, Boolean isCart) {
        ProductSpecDialog dialog = new ProductSpecDialog(this, productDetail, (color, quantity) -> {
            // 更新已选规格显示
            mBinding.tvSelectedSpec.setText(color);
            for (ProductDetailBean.SkusDTO dto : productDetail.getSkus()) {
                if (color.equals(dto.getSpecLink())) {
                    skuId = dto.getId();
                    count = quantity;
                    if (null == isCart) {
                        // TODO: 处理加入购物车或立即购买逻辑
                        Toast.makeText(this,
                                "已选择：" + color + "，数量：" + quantity,
                                Toast.LENGTH_SHORT).show();
                    } else if (!isCart) {
                        shops.clear();
                        Shop.ValidListBean shop = new Shop.ValidListBean();
                        Shop.ValidListBean.SpecificationsBean specificationsBean = getSpecificationsBean(color, dto);
                        shop.setTenantName(mBinding.getVmInfo().getMerchantDetail().getName());
                        shop.getSpecifications().add(specificationsBean);
                        shops.add(shop);
                        startActivity(new Intent()
                                .putParcelableArrayListExtra("data", shops)
                                .setClass(ProductDetailActivity.this, ConfirmOrderActivity.class));
                    } else {
                        mAccountRequester.cartAdd(skuId, count);
                    }
                    break;
                }
            }
        });
        dialog.show();
    }

    private Shop.ValidListBean.SpecificationsBean getSpecificationsBean(String color, ProductDetailBean.SkusDTO dto) {
        Shop.ValidListBean.SpecificationsBean specificationsBean = new Shop.ValidListBean.SpecificationsBean();
        specificationsBean.setCount(count);
        specificationsBean.setSelected(true);
        specificationsBean.setPicUrl(dto.getPicUrl());
        specificationsBean.setPrice(dto.getPrice());
        specificationsBean.setProperty(color);
        specificationsBean.setPicUrl(dto.getPicUrl());
        specificationsBean.setSpuName(mBinding.getVmInfo().getName());
        Shop.ValidListBean.SpecificationsBean.SkuBean skuBean = new Shop.ValidListBean.SpecificationsBean.SkuBean();
        skuBean.setId(skuId);
        specificationsBean.setSku(skuBean);
        return specificationsBean;
    }

    private String skuId = "";
    private int count;

    public class ClickProxy {
        public void openBusiness() {
            startActivity(new Intent()
                    .putExtra("title", "店铺详情")
                    .putExtra("id", mBinding.getVmInfo().getMerchantDetail().getTenantId())
                    .setClass(ProductDetailActivity.this, BusinessDetailActivity.class));
        }

        public void sendProductMessage() {

            try {
                // 发送商品消息
                ProductMessageUtils.sendProductMessage(
                        "43227074948",
                        mBinding.getVmInfo().getId(),
                        mBinding.getVmInfo().getName(),
                        mBinding.getVmInfo().getPrice(),
                        mBinding.getVmInfo().getPicUrl(),
                        mBinding.getVmInfo().getDescription(),
                        ""
                );

                Toast.makeText(ProductDetailActivity.this, "商品消息发送成功", Toast.LENGTH_SHORT).show();

            } catch (Exception e) {
                Toast.makeText(ProductDetailActivity.this, "发送失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }

    }
} 